package com.buynow.cctapi.util.filter;

import com.buynow.cctapi.util.IPAddressUtil;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import static com.buynow.cctapi.constant.ErrorCode.UNAUTHORIZED_ERROR;

/**
 * Created by jinyunni on 2017-06-05.
 */
@CommonsLog
public class URLInterceptor implements HandlerInterceptor {


    private Map<String, Integer> redisTemplate = new HashMap<String, Integer>();
    private static final Logger logger = LoggerFactory.getLogger(URLInterceptor.class);

    //在请求处理之前进行调用（Controller方法调用之前）
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String ip = IPAddressUtil.getClientIpAddress(httpServletRequest);

        String Token = httpServletRequest.getHeader("Token");

        log.info(ip + "/" + Token);

        if (!StringUtils.isBlank(Token) && !Token.equals("123456")) {
            httpServletResponse.setStatus(UNAUTHORIZED_ERROR);
            httpServletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = httpServletResponse.getWriter();
            out.print("{\"error\": \"unauthorized\",\"error_description\": \"Full authentication is required to access this resource\"}");
            return false;

        }

        if (ip == "") {

            return false;
        }


        return true;
    }

    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {


    }

    //在整个请求结束之后被调用
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //log.info(IPAddressUtil.getClientIpAddress(httpServletRequest));
    }


}